package upload

import (
	"context"
	"fmt"

	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
)

type qiniuEnter struct {
	ak          string
	as          string
	cfg         storage.Config
	putPolicy   storage.PutPolicy
	token       string
	defaultPath string
}

func (upload *qiniuEnter) SetBucket(bucket string) {
	upload.putPolicy.Scope = bucket
}

func (upload *qiniuEnter) SetKey(ak string, as string) {
	upload.ak = ak
	upload.as = as
}

func (upload *qiniuEnter) SetConfig(config interface{}) {
	upload.cfg = config.(storage.Config)
}

func (upload *qiniuEnter) Upload(file File) (FormData, error) {
	mac := qbox.NewMac(upload.ak, upload.as)
	upload.token = upload.putPolicy.UploadToken(mac)
	formUpload := storage.NewFormUploader(&upload.cfg)
	ret := storage.PutRet{}
	if file.getPath() == "" {
		upload.defaultPath = "origin"
	} else {
		upload.defaultPath = file.getPath()
	}

	fileNamePathKey := upload.defaultPath + "/" + file.getFileName()[:2] + "/" + file.getFileName()
	//TODO::扩展参数的params不知道为什么没效果
	err := formUpload.Put(context.TODO(), &ret, upload.token, fileNamePathKey,
		file.getReader(), file.getSize(), nil)

	if err != nil {
		fmt.Println(err.Error())
		return FormData{}, err
	}

	return FormData{
		Hash: file.GetMd5Hash(),
		Path: fileNamePathKey,
		Name: file.getFileName(),
		Size: file.getSize(),
	}, nil

}

// UploadCapture , 直接网络抓取
func (upload *qiniuEnter) UploadCapture(url string) {
	mac := qbox.NewMac(upload.ak, upload.as)
	cfg := storage.Config{
		// 是否使用https域名进行资源管理
		UseHTTPS: true,
	}
	bucketManager := storage.NewBucketManager(mac, &cfg)
	fetchRet, err := bucketManager.FetchWithoutKey(url, upload.putPolicy.Scope)
	if err != nil {
		fmt.Println("fetch error,", err)
	} else {
		fmt.Println(fetchRet.String())
	}

}
